<?php

namespace App\Models;

use App\ModelFilters\QHSchoolFilter;
use Auth;
use DB;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Qh_School extends BaseModel
{
    protected $table = 'qh_schools';

    protected $appends = ['followed', 'tagsList', 'spec'];

    protected $guarded = [];

    public function getProvinceAttribute($v) {
        return json_decode($v);
    }

    /**
     * 用户的关注状态
     * @return bool
     */
    public function getFollowedAttribute(): bool
    {
        $followed = false;
        if (Auth::guard('api')->check()) {
             $followed = (bool)DB::table('qh_user_follow_school')->where('schoolId', $this->id)->where('userId', Auth::guard('api')->user()->id)->first();
        }
        return $followed;
    }

    public function spec(): BelongsToMany
    {
        return $this->belongsToMany(Qh_SchoolSpec::class, 'qh_school_spec_real', 'schoolId', 'schoolSpecId');
    }

    public function modelFilter(): ?string
    {
        return $this->provideFilter(QHSchoolFilter::class);
    }

    public function getSpecAttribute(): array
    {
        return $this->spec()->pluck('schoolSpecId')->toArray();
    }

    //public function getTagsAttribute($v) {
    //    return array_filter(explode(',', $v));
    //}

    //public function setTagsAttribute($v): string
    //{
    //    return implode(',', $v);
    //}

    public function getTagsListAttribute() {
        return array_filter(explode(',', $this->tags));
    }

    public function getImagesAttribute($v) {
        return array_filter(explode(',', $v));
    }

    public function getLogoAttribute($v) {
        return replaceStaticFileUrlInString($v, '/daxuetupian/', '/daxuetupian/');
    }
}
